package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.LambdaUpdateChainWrapper;
import com.tanhua.sso.enums.SexEnum;
import com.tanhua.sso.mapper.UserInfoMapper;
import com.tanhua.sso.mapper.UserMapper;
import com.tanhua.sso.pojo.User;
import com.tanhua.sso.pojo.UserInfo;
import com.tanhua.sso.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
public class UserInfoService {
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private FaceEngineService faceEngineService;
    @Autowired
    private PicUploadService picUploadService;

    public Boolean saveUserInfo(Map<String, String> param, String token) {
        //判断token是否有效
        User user = userService.queryUserByToken(token);

        if (null == user) {
            return false;//user不存在
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(Long.parseLong(user.getId()));
        userInfo.setSex(StringUtils.equalsIgnoreCase(param.get("gender"), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setNickName(param.get("nickname"));
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setCity(param.get("city"));
        int i = userInfoMapper.insert(userInfo);
        if (i == 1) {
            return true;
        }
        return false;
    }


    public Boolean saveUserLogo(MultipartFile file, String token) {
        //判断token是否有效
        User user = userService.queryUserByToken(token);
        if (user == null) {//token无效
            return false;
        }
        try {
            //检查上传的图片是否为人像
            boolean portrait = faceEngineService.checkIsPortrait(file.getBytes());
            if (!portrait) {
                return false;//非人像,返回false
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将图片上传到阿里云oss中
        PicUploadResult result = picUploadService.upload(file);
        if (StringUtils.isEmpty(result.getName())) {
            //上传失败
            return false;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(result.getName());


        UpdateWrapper<UserInfo> wrapper = new UpdateWrapper<>();
        wrapper.eq("user_id", user.getId());

        return userInfoMapper.update(userInfo, wrapper) == 1;

    }

}
